package com.youdianstar.app.common.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.appcompat.widget.AppCompatEditText;

import com.youdianstar.app.common.R;
import com.youdianstar.app.common.util.StrUtil;

import java.util.Objects;

/**
 * File: SearchEditText
 * author: zhangjiabiao Create on 2019/11/29 18:12
 * Change (from 2019/11/29)
 * --------------------------------
 * description:
 * ----------------------------
 */
public class SearchEditText extends AppCompatEditText implements View.OnKeyListener, View.OnFocusChangeListener, TextWatcher {
    /**
     * 是否显示在左边
     */
    public boolean isShowNormal = true;
    /**
     * 是否点击软键盘搜索
     */
    public boolean pressSearch = true;
    /**
     * 软键盘搜索键监听
     */
    public OnSearchClickListener listener;
    /**
     * 键盘监听接口
     */
    OnKeyBoardHideListener onKeyBoardHideListener;


    private Drawable[] drawables; // 控件的图片资源
    private Drawable drawableLeft, drawableDel; // 搜索图标和删除按钮图标
    private boolean isClean;
    private boolean isclick;
    private boolean isCleanEnable = true;
    /**
     * 是否显示删除按钮
     */
    private boolean isShowDel = true;

    public void setOnSearchClickListener(OnSearchClickListener listener) {
        this.listener = listener;
    }

    public interface OnSearchClickListener {
        void onSearchClick(View view);
    }

    public void setOnKeyBoardHideListener(OnKeyBoardHideListener onKeyBoardHideListener) {
        this.onKeyBoardHideListener = onKeyBoardHideListener;
    }

    public interface OnKeyBoardHideListener {
        void onKeyHide(int keyCode, KeyEvent event);
    }

    public SearchEditText(Context context) {
        this(context, null);
        init();
    }

    public SearchEditText(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.editTextStyle);
        init();
    }

    public SearchEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {

        setOnFocusChangeListener(this);
        setOnKeyListener(this);
        addTextChangedListener(this);

        drawables = getCompoundDrawables();
    }

    public boolean isShowDel() {
        return isShowDel;
    }

    public void setShowDel(boolean showDel) {
        isShowDel = showDel;
    }

    public boolean isCleanEnable() {
        return isCleanEnable;
    }

    public void setCleanEnable(boolean cleanEnable) {
        isCleanEnable = cleanEnable;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        drawableLeft = drawables[0];
        if (isShowNormal) { // 如果是默认样式，直接绘制
            if (length() < 1) {
                drawableDel = null;
            }
            this.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, drawableDel, null);
            super.onDraw(canvas);
        } else { // 如果不是默认样式，需要将图标绘制在中间
            float textWidth = getPaint().measureText(getHint().toString());
            int drawablePadding = getCompoundDrawablePadding();
            int drawableWidth = null != drawableLeft ? drawableLeft.getIntrinsicWidth() : 0;
            float bodyWidth = textWidth + drawableWidth + drawablePadding;
            canvas.translate((getWidth() - bodyWidth - getPaddingLeft() - getPaddingRight()) / 2, 0);
            super.onDraw(canvas);
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        // 被点击时，恢复默认样式
        if (!pressSearch && TextUtils.isEmpty(getText().toString())) {
            isShowNormal = true;
        }
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == 1 && null != onKeyBoardHideListener) {
            super.onKeyPreIme(keyCode, event);
            onKeyBoardHideListener.onKeyHide(keyCode, event);
            return false;
        }
        return super.onKeyPreIme(keyCode, event);
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        pressSearch = (keyCode == KeyEvent.KEYCODE_ENTER);
        if (pressSearch && listener != null) {
            hideSoft(v);
            if (event.getAction() == KeyEvent.ACTION_UP) {
                pressSearch = false;
                listener.onSearchClick(v);
            }
        }
        return false;
    }

    /*隐藏软键盘*/
    public void hideSoft(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                isClean = (event.getX() > (getWidth() - getTotalPaddingRight()))
                        && (event.getX() < (getWidth() - getPaddingRight()));
                if (isClean && isShowDel) {
                    setText("");
                }
//                isclick = (event.getX()>getPaddingLeft())&&(event.getX()<getTotalPaddingLeft());
//                if (isclick){
//                    listener.onSearchClick(this);
//                }
//                setInputType(isclick? InputType.TYPE_NULL:InputType.TYPE_CLASS_TEXT);
                break;

            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void afterTextChanged(Editable arg0) {
        if (this.length() < 1) {
            drawableDel = null;
        } else {
            if (isShowDel)
                drawableDel = this.getResources().getDrawable(R.drawable.edit_clear);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    }

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    }

    public void clearDelIcon() {
        drawableDel = null;
    }

    public void showDelIcon() {
        if (!StrUtil.isEmpty(Objects.requireNonNull(getText()).toString())) {
            drawableDel = this.getResources().getDrawable(R.drawable.edit_clear);
        }
    }
}
